package com.bckj.fastboot.iot.biz.service.impl;

import com.bckj.fastboot.core.extra.cache.CacheOps;
import com.bckj.fastboot.iot.biz.convert.IotProtocolConvert;
import com.bckj.fastboot.iot.biz.convert.IotProtocolItemConvert;
import com.bckj.fastboot.iot.biz.repository.IotProtocolItemRepository;
import com.bckj.fastboot.iot.biz.repository.IotProtocolRepository;
import com.bckj.fastboot.iot.biz.service.IotProtocolService;
import com.bckj.fastboot.iot.common.constant.IotCacheConstants;
import com.bckj.fastboot.iot.common.dto.request.IotProtocolRequest;
import com.bckj.fastboot.iot.common.entity.IotProtocol;
import com.bckj.fastboot.iot.common.entity.IotProtocolItem;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * IotProtocolServiceImpl
 *
 * @author wfc
 **/

@Service
@RequiredArgsConstructor
public class IotProtocolServiceImpl implements IotProtocolService {
    private final IotProtocolRepository iotProtocolRepository;
    private final IotProtocolItemRepository iotProtocolItemRepository;
    private final IotProtocolConvert iotProtocolConvert;
    private final IotProtocolItemConvert iotProtocolItemConvert;
    private final CacheOps cacheOps;

    @Override
    public boolean save(IotProtocolRequest request) {
        String code = request.getCategory() + request.getType();
        request.setCode(code);
        IotProtocol entity = iotProtocolConvert.toEntity(request);
        boolean saved = iotProtocolRepository.save(entity);
        if (saved) {
            List<IotProtocolItem> list = request.getItems()
                    .stream()
                    .map(p -> {
                        var item = iotProtocolItemConvert.toEntity(p);
                        item.setProtocolCode(code);
                        return item;
                    }).toList();
            iotProtocolItemRepository.saveBatch(list, 1000);
        }
        return saved;
    }

    @Override
    public boolean update(IotProtocolRequest request) {
        return false;
    }

    @Override
    public void clearItemsCache(String protocolCode, String[] cmdArr) {
        Assert.notNull(protocolCode, "protocolCode can not be null");
        var cache = cacheOps.redisCache(IotCacheConstants.IOT_PROTOCOL_ITEM_CACHE);
        if (cmdArr == null || cmdArr.length == 0) {
            cache.evict(protocolCode);
        } else {
            for (String cmd : cmdArr) {
                cache.evict(protocolCode + cmd);
            }
        }
    }
}
